const router = require('koa-router')()
const mongoose = require('mongoose')
const statsfn = require('../lib/statsfn')
const Comment = mongoose.model('Comment')
const User = mongoose.model('User')
const crypto = require('crypto')

const Image = mongoose.model('Image')

router.get('/', async (ctx, next) => {
  const images = await Image.find({})
    .sort({createAt: -1})
    .limit(20)
  const stats = await statsfn()
  const Allcomments = await Comment.find()
 	  .sort({createdAt: -1})
 	  .limit(3)
  await ctx.render('index', {
    title: '图片共享',
    images, stats, Allcomments, user: ctx.session.user
  })
})

router.get('/login', async ctx => {
  await ctx.render('login')
})

router.post('/login', async ctx => {
  let {username, password} = ctx.request.body
  //  if(username === 'tom' && password === '123') {
  //    ctx.session.user = {nickname: '汤姆', username: 'tom'}
  //   ctx.redirect('/')
  let user = await User.find({username: username})
  const hash = crypto.createHash('md5')
  hash.update(password)
  password = hash.digest('hex')

  if(password === user[0].password){   
    ctx.session.user = user[0]
    ctx.redirect('/')
  }
})

router.get('/register', async ctx => {
  await ctx.render('register')
})

router.post('/register', async ctx => {
  let {username, password, nickname, email} = ctx.request.body
  const hash = crypto.createHash('md5')
  hash.update(password)
  password = hash.digest('hex')

  const user = await User.create({
    username, password, nickname, email
  })
  ctx.redirect('/')
})

router.get('/logout', async ctx =>{
  ctx.session.user = undefined
  ctx.redirect('/')
})
module.exports = router
